let settle = require('axios/lib/core/settle')
let buildURL = require('axios/lib/helpers/buildURL')
let buildFullPath = require('axios/lib/core/buildFullPath')
import isUploadFile from "./isUploadFile.js"

function format(config, resolve, reject) {
  const fullPath = buildFullPath(config.baseURL, config.url)
  const requestHeaders = config.headers

  const uniConfig = {
    ...config,
    url: buildURL(fullPath, config.params, config.paramsSerializer),
    header: requestHeaders,
  }

  // uni.request data内部处理逻辑，需要object，提前parse
  // https://uniapp.dcloud.io/api/request/request
  if (typeof config.data === 'string') {
    config.data = JSON.parse(config.data)
  }

  if (config.method === 'get') {
    // 兼容 get 时的 params 字段
    uniConfig.data = config.data ? config.data : config.params
  } else {
    if (isUploadFile(config)) {
      delete requestHeaders['Content-Type'] // Let the browser set it
      if (config.formData) {
        uniConfig.formData = config.formData
      } else {
        uniConfig.formData = config.data
      }
    } else {
      uniConfig.data = config.data
    }
  }

  // HTTP basic authentication
  if (config.auth) {
    let username = config.auth.username || ''
    let password = unescape(encodeURIComponent(config.auth.password)) || ''
    requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password)
  }

  uniConfig.complete = function(response) {
    // console.log("uniConfig.complete", response)
    // 暂时不明白为什么要判断 responseType === 'text'，也许返回结果是有多种格式的，但是目前没碰到。
    // let responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
    let result = {
      data: response.data,
      status: response.statusCode,
      header: response.header,
      config: config,
      message: response.errMsg,
    }
    settle(resolve, reject, result)
  }

  return uniConfig
}

export default format
